package com.yy.web.pm.alarm.service.Impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.io.unit.DataUnit;
import com.yy.web.pm.alarm.alarmDto.AlarmDtoList;
import com.yy.web.pm.billboard.domain.BillboardData;
import com.yy.web.pm.billboard.domain.Dto.BillboardDto;
import com.yy.web.pm.billboard.mapper.BillboardDataMapper;
import com.yy.web.pm.billboardRemove.domain.BillboardRemove;
import com.yy.web.pm.billboardRemove.mapper.BillboardRemoveMapper;
import com.yy.web.pm.operateExamine.domain.ExamineOperate;
import com.yy.web.pm.operateExamine.domain.FileData;
import com.yy.web.pm.operateExamine.mapper.ExamineOperateMapper;
import com.yy.web.pm.operateExamine.mapper.FileDataMapper;
import com.yy.web.pm.patrol.domain.PeoplePatrol;
import com.yy.web.pm.patrol.mapper.PeoplePatrolMapper;
import com.yy.web.pm.shopPeople.domain.ShopPeople;
import com.yy.web.pm.shopPeople.mapper.ShopPeopleMapper;
import com.yy.web.pm.until.CodeGenerator;
import com.yy.web.pm.until.UserNotFoundException;
import com.yy.web.pm.user.domain.User;
import com.yy.web.pm.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.yy.web.pm.alarm.mapper.AlarmDateMapper;
import com.yy.web.pm.alarm.domain.AlarmDate;
import com.yy.web.pm.alarm.service.AlarmDateService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AlarmDateServiceImpl implements AlarmDateService {

    @Resource
    private AlarmDateMapper alarmDateMapper;
    @Autowired
    private ExamineOperateMapper examineOperateMapper;  //操作记录
    @Autowired
    private FileDataMapper fileDataMapper; //归档记录
    @Autowired
    private UserMapper userMapper; //用户查询
    @Autowired
    private ShopPeopleMapper shopPeopleMapper;//商家
    @Autowired
    private PeoplePatrolMapper peoplePatrolMapper; // 巡检人员
    @Autowired
    private BillboardDataMapper billboardDataMapper;// 广告牌
    @Autowired
    private BillboardRemoveMapper billboardRemoveMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return alarmDateMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(AlarmDate record) {
        String string = record.getImage().stream().filter(s -> !s.isEmpty() && s != null).collect(Collectors.joining(","));
        record.setAlarmImage(string);
        return alarmDateMapper.insert(record);
    }

    @Override
    public int insertSelective(AlarmDate record) {
        return alarmDateMapper.insertSelective(record);
    }

    @Override
    public AlarmDate selectByPrimaryKey(Integer id) {
        return alarmDateMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(AlarmDate record) {
        return alarmDateMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(AlarmDate record) {
        return alarmDateMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<AlarmDate> selectAlarmAll(AlarmDate alarmDate) {
        return alarmDateMapper.selectAlarmAll(alarmDate);
    }

    /**
     * @param alarmDate:
     * @Title:Adminexamine
     * @Description: 方法描述: 管理员审核判断数据是否是真实报警，真实报警则派发，否则则取消报警，关闭工单，记录存档
     */
    @Override
    public String AdminUpdateExamine(AlarmDate alarmDate, String opedId) {
        //处理状态 处理状态 0:未处理 1：存在安全隐患 2：已取消 3 巡检员已经巡检 4:勒令整改 5:拆除 -1已完成
        User user = getUser();
        //判断是否是真实报警
        if (alarmDate.getAlarmState().equals("2")) {
            //告警有误，取消告警，关闭工单，记录存档（操作表和存档）
            recordOperate(alarmDate, examineOperateMapper, user);//记录操作
            recordFile(alarmDate, fileDataMapper, user);//记录存档
            alarmDateMapper.AdminUpdateExamine(alarmDate);
            return "告警有误，取消告警，关闭工单，记录存档";
        }
        //任务下发

        else if (alarmDate.getAlarmState().equals("1")) {
            //     真实报警，将信息派发给巡检员，巡检员去查看并且上传巡检信息，并且推送给商家,需要传入商家id和巡检人id(用户id)
            // 告警表关联用户表，然后关联巡检表，在巡检表新建信息
            // 任务下发
            alarmDateMapper.AdminUpdateExamine(alarmDate); //通知存在安全隐患
            Taskdistribution(user, alarmDate, peoplePatrolMapper);//告警巡检任务派发
            // 商家整改任务派发
            shopPeopleMapper.updateByPrimaryKey(new ShopPeople().setId(alarmDate.getShopId()).setIsjudge("1").setChangeNotes(alarmDate.getAlarmNotes()));
            recordOperate(alarmDate, examineOperateMapper, user);//记录操作
            return "任务下发成功";
        }
        // 商家整改派发
        if (alarmDate.getAlarmState().equals("4")) {
            shopPeopleMapper.updateByPrimaryKey(new ShopPeople().setIsjudge("2").setChangeNotes(alarmDate.getAlarmNotes()));
            recordOperate(alarmDate, examineOperateMapper, user);//记录操作
            recordFile(alarmDate, fileDataMapper, user);//记录存档
            return "店铺整改任务";
        }

        if (alarmDate.getAlarmState().equals("5")) {
            //     店铺拆除，先发给巡检员，巡检员查看拆除前的后，在由巡检员发送给商家，商家拆除后，由巡检员在查看一才，在提交给管理员审核
            //新增拆除表记录
            //获取广告牌编号
            BillboardData data = billboardDataMapper.selectShopById(alarmDate.getShopId());
            BillboardRemove billboardRemove = new BillboardRemove()
                    .setBillboardNumber(data.getAdvertisementNumber())
                    .setRemoveTime(new Date())
                    .setRemovePeople(user.getUsername())
                    .setRemovePeoplePhone(user.getPhone())
                    .setNotes(alarmDate.getAlarmNotes())
                    .setShopId(String.valueOf(alarmDate.getShopId()));
            billboardRemoveMapper.insert(billboardRemove);




            // shopPeopleMapper.updateByPrimaryKey(new ShopPeople().setIsjudge("3").setChangeNotes(alarmDate.getAlarmNotes()));
            // recordOperate(alarmDate, examineOperateMapper, user);//记录操作
            // recordFile(alarmDate, fileDataMapper, user);//记录存档
            return "店铺拆除任务下发成功";
        }
        return null;

    }

    private User getUser() {
        //获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String openId = extractOpenId(authentication.getName());
        User user = userMapper.getUserByOpenId(openId);//获取当前用户信息
        return user;
    }

    /**
     * @param user:
     * @param alarmDate:
     * @param peoplePatrolMapper:
     * @Title:Taskdistribution
     * @Description: 方法描述:告警巡检记录添加
     */

    private void Taskdistribution(User user, AlarmDate alarmDate, PeoplePatrolMapper peoplePatrolMapper) {
        PeoplePatrol peoplePatrol = new PeoplePatrol()
                .setPatrolPeople(user.getUsername())
                .setUserId(Math.toIntExact(user.getId()))
                .setPartrolStore(alarmDate.getAlarmShop())
                .setPartrolAddress(alarmDate.getAlarmAddress())
                .setPartrolLevel(alarmDate.getAlarmLevel())
                .setPartrolTime(alarmDate.getAlarmTime())
                .setPartrolType("告警巡检")
                .setPartrolNumber(alarmDate.getAlarmNumber())
                .setPartrolProgress("0")
                .setPartrolNotes(alarmDate.getAlarmNotes());
        peoplePatrolMapper.insert(peoplePatrol);
    }

    /**
     * @param alarmDate:
     * @param fileDataMapper:
     * @param user:
     * @Title:recordFile
     * @Description: 方法描述:记录归档
     */

    public void recordFile(AlarmDate alarmDate, FileDataMapper fileDataMapper, User user) {
        FileData fileData = new FileData()
                .setOperatePeopele(user.getUsername())
                .setOperateResult(alarmDate.getAlarmState())
                .setOperateEventId(alarmDate.getId().toString())
                .setOperateTime(DateTime.now());
        fileDataMapper.insert(fileData);
    }

    /**
     * @param alarmDate:
     * @param examineOperateMapper:
     * @param user:
     * @Title:recordOperate
     * @Description: 方法描述:操作记录
     */

    public void recordOperate(AlarmDate alarmDate, ExamineOperateMapper examineOperateMapper, User user) {
        ExamineOperate operate = new ExamineOperate()
                .setExaminePeople(user.getUsername())//审核人
                .setEventId(alarmDate.getId())//审核任务id
                .setExamineTime(DateTime.now())//审核时间
                .setExamineType(alarmDate.getAlarmType())//审核告警类型
                .setExamineOperate(alarmDate.getAlarmState());//审核状态
        examineOperateMapper.insert(operate);
    }

    /**
     * @ClassName: AlarmDateServiceImpl
     * @Description: 类描述:使用正则表达式获取openId
     * @date: 2025/4/16
     */
    public static String extractOpenId(String input) {
        // 定义正则表达式模式
        Pattern pattern = Pattern.compile("openId=([^,]+)");
        Matcher matcher = pattern.matcher(input);
        // 查找匹配项
        if (matcher.find()) {
            return matcher.group(1);
        }
        throw new UserNotFoundException("用户不存在!");
    }

    @Override
    public int updateBatch(List<AlarmDate> list) {
        return alarmDateMapper.updateBatch(list);
    }

    @Override
    public int batchInsert(List<AlarmDate> list) {
        return alarmDateMapper.batchInsert(list);
    }

    //巡检人列表
    @Override
    public List<AlarmDtoList> selectAlarmAllDate(AlarmDtoList alarmDtoList) {
        return alarmDateMapper.selectAlarmAllDate(alarmDtoList);
    }

    @Override
    public List<BillboardDto> AdminUpdateExamineAd(BillboardDto billboardDto) {

        return null;
    }

    @Override
    public String selectBillBoardList(BillboardDto billboardDto) {
        if (billboardDto.getShopStateRif().equals("1")) {
            //修改广告牌RIf
            billboardDataMapper.updateByPrimaryKey(new BillboardData().setAdvertisementRif(billboardDto.getBillboardRif()));
            // 修改商家店铺广告牌状态
            shopPeopleMapper.updateByPrimaryKey(new ShopPeople().setChangeJudge("0"));
            User user = getUser();
            //记录存档
            FileData fileData = new FileData()
                    .setOperatePeopele(user.getUsername())
                    .setOperateResult("审核通过,下发新的Rfid")
                    .setOperateDecision("审核通过")
                    .setOperateEventId(billboardDto.getShopId())
                    .setOperateTime(new Date());
            fileDataMapper.insert(fileData);
            return "审核通过";

        }


        return null;
    }

    //查看商家的修改Rif的列表
    @Override
    public List<BillboardDto> ShopUpdateAllList(BillboardDto billboardDto) {
        billboardDto.setChangeJudge("1");
        return alarmDateMapper.selectBillBoardList(billboardDto);
    }

    // 处理广告牌到期时间
    @Override
    public void AdminUpdateExamineAdTime(BillboardDto billboardDto) {
        User user = getUser();
        if (billboardDto.getShopState().equals("0")) {
            String string = billboardDto.getBillboardList().stream().filter(s -> s != null && !s.isEmpty()).collect(Collectors.joining(","));
            //交给第三方检测机构
            BillboardData data = new BillboardData()
                    .setAdvertisementNumber(billboardDto.getBillboardNumber())
                    .setAdvertisementName(billboardDto.getBillboardName())
                    .setAdvertisementAddress(billboardDto.getShopAdress())
                    .setAdvertisementTestTime(new Date())
                    .setAdvertisementStarttime(convertStringToDate(billboardDto.getBillboardStartTime()))
                    .setAdvertisementEndtime(convertStringToDate(billboardDto.getBillboardEndTime()))
                    .setDetectionPeople(billboardDto.getBillboardCheckPeople())
                    .setDetectionImage(string)
                    .setShopId(billboardDto.getShopId());
            billboardDataMapper.insert(data);

        }
        //进入拆除流程
        shopPeopleMapper.updateByPrimaryKey(new ShopPeople().setIsjudge("3"));// 给商家的设置为拆除
        //然后商家向巡检员发送信息，记录操作
        ExamineOperate operate = new ExamineOperate()
                .setExaminePeople(user.getUsername())//审核人
                .setEventId(Integer.valueOf(billboardDto.getShopId()))//审核任务id
                .setExamineTime(DateTime.now())//审核时间
                .setExamineType("广告牌拆除")//审核告警类型
                .setExamineOperate("1");//审核状态
        examineOperateMapper.insert(operate);
    }

    /**
     * @param alarmDate:
     * @Title:selectShopAllDate
     * @Description: 方法描述: 获取商家列表
     */
    @Override
    public List<BillboardDto> selectShopAllDate(BillboardDto alarmDate) {

        return alarmDateMapper.selectShopAllDate(alarmDate);
    }
//告警数据列表
    @Override
    public List<AlarmDate> selectAlarmList(PeoplePatrol patrol) {
        User user = getUser();
        patrol.setUserId(Math.toIntExact(user.getId()));
        return alarmDateMapper.selectAlarmList(patrol);
    }

    public Date convertStringToDate(String dateString) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 根据实际格式调整
        try {
            return dateFormat.parse(dateString);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Invalid date format: " + dateString, e);
        }
    }

}

